package cn.com.jsepc.rep.comm;

import java.io.IOException;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Hashtable;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.log4j.Logger;

import cn.com.jsepc.appframe.system.AppframeOrgClient;
import cn.com.jsepc.appframe.system.domain.BaseOrg;
import cn.com.jsepc.appframe.system.domain.SpecialOrg;
import cn.com.jsepc.appframe.system.domain.SysSpRole;
import cn.com.jsepc.appframe.system.domain.SysSystem;
import cn.com.jsepc.appframe.system.domain.User;
import cn.com.jsepc.appframe.system.service.AppframeOrg;

import com.jarp.db.DAO;


public class LoginFilter implements Filter {
	/**
	 * Logger for this class
	 */
	private static final Logger logger = Logger.getLogger(LoginFilter.class);

	/**
	 * Constructor of the object.
	 */

	public LoginFilter() {
		super();
	}

	public static boolean isContains(String container, String[] regx) {
		boolean result = false;

		for (int i = 0; i < regx.length; i++) {
			if (container.indexOf(regx[i]) != -1) {
				return true;
			}
		}
		return result;
	}

	public FilterConfig config;

	public void setFilterConfig(FilterConfig config) {
		this.config = config;
	}

	public FilterConfig getFilterConfig() {
		return config;
	}

	public void doFilter(ServletRequest request, ServletResponse response,
			FilterChain chain) throws IOException, ServletException {

		HttpServletRequest req = (HttpServletRequest) request;

		HttpServletResponse rep = (HttpServletResponse) response;
		response.setContentType("text/html;charset=UTF-8");
		HttpSession session = req.getSession(true);
		String userAddr = request.getServerName();

		rep.addHeader("P3P", "CP=CAO PSA OUR");

		String userid = "-1";

		userid = (String) session.getAttribute("midawa_UserCode");
		// 调过loginfilter方法，不写用户信息
		if (session.getAttribute("midawa_UserCode") != null) {
			chain.doFilter(request, response);
			return;
		} else {
			try {
				long beginTime = System.currentTimeMillis();

				String unIncludeStrings = config
						.getInitParameter("unIncludeStrings");
				String[] unIncludeList = unIncludeStrings.split(";");
				if (this.isContains(req.getRequestURI(), unIncludeList)) {
					chain.doFilter(request, response);
					return;
				}
				String key = config
				.getInitParameter("Key");
				if(key==null||key.equals("")){
					key="9DB0B5B9C1F49708";
				}
				com.jsepc.portal.sso.DES.setKey(key);
				// 增加对国网用户的特殊处理
				if (request.getParameter("comp") != null
						&& request.getParameter("usercode") != null) {
					// 此登录为国网用户,从数据库中取出国网用户相对应的usercode
					userid = request.getParameter("usercode");
				} else {
					userid = com.jsepc.portal.sso.Helper
							.newGenerateUserCode(req);
				}

				// 如果没有获得统一认证用户id，从统一框架的模拟接口取
				if (userid == null || "-1".equals(userid)) {
					userid = request.getParameter("appframeuserid");
				}
				if (userid == null || userid.equals("-1")) {
					String authPath = config.getInitParameter("AuthPath");
					//System.out.println("authPath:" + authPath);
					rep.sendRedirect(authPath
							+ URLEncoder.encode(req.getRequestURL().toString()
									+ "?" + req.getQueryString()));		
				} else {
					Long ln = new Long(Long.parseLong(userid));
					session.setAttribute("midawa_UserCode", userid);					
					//调用统一框架服务，获得权限相关数据。
					AppframeOrg appframeorg= AppframeOrgClient.getInstance();
					//获取用户信息
					User user=appframeorg.getUserById(ln);
					BaseOrg org=appframeorg.getBaseOrgOfCorp(user.getBaseorg_id());
					session.setAttribute("midawa_UserName", user.getName());
					session.setAttribute("midawa_UserDept",String.valueOf(user.getBaseorg_id()));
					session.setAttribute("midawa_UserOrgName",user.getBaseorg());
					session.setAttribute("midawa_UserPwd", user.getPassword());
					
					//获取系统信息 
					String systemCode=config.getInitParameter("SystemCode");
					if(systemCode==null||systemCode.equals("")){
						systemCode="MIDAWA";
					}
					SysSystem system = appframeorg.getSystemByCode(systemCode);
					SysSpRole[] sysSp= appframeorg.getSpRolesByUser(ln,system.getId(),null);
					//记录当前用户所属角色id ，一个用户可能对应多个角色ID
					String roles="";
					//记录当前用户所属角色的公司ID。
					Hashtable corphst=new Hashtable();
					String corps="";
					StringBuffer specialOrgInfo=new StringBuffer();
					SpecialOrg corpArray []=new SpecialOrg[sysSp.length];
					for(int i=0;i<sysSp.length;i++){
						SpecialOrg corp= appframeorg.getSpecialOrgsOfCorp(sysSp[i].getSpecialorgid());
						corpArray[i]=corp;
						if(i==0){
							roles+=sysSp[i].getId().toString();
							if(!corphst.containsKey(corp.getUnicode())){
								corphst.put(corp.getUnicode(),corp.getUnicode());
								corps+=corp.getUnicode();
							}
						}else{
							roles+=","+sysSp[i].getId().toString();
							if(!corphst.containsKey(corp.getUnicode())){
								corphst.put(corp.getUnicode(),corp.getUnicode());
								corps+=","+corp.getUnicode();
							}
						}
					}
					//按级别排序
					if(corpArray.length>1){
						for(int i=1;i<corpArray.length;i++){
							int level=corpArray[i-1].getLevel();
							if(corpArray[i].getLevel().intValue()<level){
								SpecialOrg tmp=corpArray[i];
								corpArray[i]=corpArray[i-1];
								corpArray[i-1]=tmp;
							}
						}
					}
					Hashtable speorgIdhst=new Hashtable();
					for(int i=0;i<corpArray.length;i++){
						if(speorgIdhst.keySet().size()>0){
							if(speorgIdhst.containsKey(corpArray[i].getId()) || speorgIdhst.containsKey(corpArray[i].getParentId())){
								continue;
							}
						}
						if(specialOrgInfo.length()>0){
							specialOrgInfo.append(ConstUtil.splitChar+corpArray[i].getId()+",ORG"+","+corpArray[i].getCode()+","+corpArray[i].getUnicode()+","+corpArray[i].getIsLeaf()+","+corpArray[i].getLevel()+","+corpArray[i].getName());
						}else{
							specialOrgInfo.append(corpArray[i].getId()+",ORG"+","+corpArray[i].getCode()+","+corpArray[i].getUnicode()+","+corpArray[i].getIsLeaf()+","+corpArray[i].getLevel()+","+corpArray[i].getName());
						}
						speorgIdhst.put(corpArray[i].getId(), corpArray[i].getId());
					}
					///*打印注释
					System.out.println("User Name:"+user.getName());
					System.out.println("User id:"+user.getId());
					System.out.println("User roles:"+roles);
					System.out.println("User corps:"+corps);
					System.out.println("User specialOrgInfo:"+specialOrgInfo.toString());
					//*/
					//所属角色ID
					session.setAttribute("midawa_UserRoles",roles);
					//所属单位ID
					session.setAttribute("midawa_Usercorps",corps);
					session.setAttribute("midawa_specialOrgInfo",specialOrgInfo.toString());
					long endTime = System.currentTimeMillis();
					System.out
							.println("LoginTime,get information from the appframe webservice>>>>>"
									+ (endTime - beginTime) + "ms");
					chain.doFilter(request, response);
				}
			} catch (Exception exp) {
				exp.printStackTrace();
			}
		}

	}

	public void destroy() {
		this.config = null;
	}

	public void init(FilterConfig filterConfig) throws ServletException {
	
		this.config = filterConfig;
	}
}
